﻿using System.IO;
using System.Linq;
using SpCop.Core.Model;
using SpCop.Model;

namespace SpCop.General.Modules
{
    
    class PageLayoutsOnlyContainContentControls : ModuleRuleBase
    {
        public PageLayoutsOnlyContainContentControls()
            : base(a => a == "_catalogs/masterpage")
        {
            
        }

        protected override void VisitModule(Package package, Feature feature, Element item)
        {
                foreach (var file in GetFileElements(item.Xml,".aspx"))
                {
                    var urlValue = file.Attribute("Url").Value;
                    var path = Path.Combine(Path.Combine(package.Path, feature.Folder), urlValue);

                    if (!File.Exists(path))
                    {
                        // its not the purpose of this rule, this would cause double logging of a filenot found under different reasons and rules.
                    }
                    else
                    {
                     
                                var parsed = GetParsedContentFile(path);

                                // TODO : this rule is not working.
                                foreach (var contentPart in parsed.Parts.Where(a=>a.Type == MixedContentTypes.Directive))
                                {
                                    var s = contentPart.Match.ToString();
                                    
                                    if(!s.StartsWith("<%@ Page"))
                                        continue;
                                    

                                    var startIndex = s.IndexOf("Inherits") + 10;
                                    var d = s.Substring(startIndex, s.IndexOf("\"",startIndex+1)-startIndex);
                                    AddProblem("Found inheritance in page : {0}",d);
                                }
                                break;
                        
                    }
                }
            
        }
    }


   
}